import instance from './http';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 封装GET请求
export function get<T>(url: string, params?: any): Promise<T | void> {
  return instance
    .get<T>(url, { params })
    .then((response: any) => {
      if (response.data.code !== 200) {
        ElMessage.error('失败');
      }
      return response.data;
    })
    .catch((error) => {
      throw error;
    });
}

// 封装POST请求
export function post<T>(url: string, data?: any): Promise<T> {
  return instance
    .post<T>(url, data)
    .then((response: any) => {
      if (response.data.code !== 200) {
        ElMessage.error('失败');
      }
      return response.data;
    })
    .catch((error) => {
      throw error;
    });
}

// put
export function put<T>(url: string, data?: any): Promise<T> {
  return instance
    .put<T>(url, data)
    .then((response: any) => {
      if (response.data.code !== 200) {
        ElMessage.error('失败');
      }
      return response.data;
    })
    .catch((error) => {
      throw error;
    });
}

//delete
export function del<T>(url: string): Promise<T> {
  return instance
    .delete<T>(url)
    .then((response: any) => {
      if (response.data.code !== 200) {
        ElMessage.error('失败');
      }
      return response.data;
    })
    .catch((error) => {
      throw error;
    });
}

/* 上传文件 */
export function uploadFile(url: string, params = {}, msg: any, callback: any) {
  const formData = new FormData();
  for (const key in params) {
    // @ts-ignore
    formData.append(key, params[key]);
  }
  return axios({
    url: url,
    method: 'post',
    data: formData
  })
    .then((response) => {
      if (response.data.code === 200) {
        if (msg != null && msg.length != 0) {
          // Message.success(msg);
        } else if (response.data.message != null && response.data.message.length != 0) {
          // Message.success(response.data.message);
        }
        callback(response.data);
      } else {
        // Message.error(response.data.message);
      }
    })
    .catch((error) => {
      throw error;
    });
}

/* 文件下载 */
export function downloadFile(url: string, params = {}, calback: any) {
  axios({
    method: 'get',
    url: url,
    params: params,
    responseType: 'blob'
  })
    .then((response) => {
      const type = response.data.type;
      if (type == 'application/json') {
        // Message.error('文件不存在');
        return;
      }
      // 进行文件下载
      const filename = response.headers['content-disposition'];
      if (filename == null || filename == '' || filename == undefined) {
        // Message.error('下载失败');
        return;
      }
      const data = response.data;
      if (!data) {
        return;
      }
      // 构造a标签 通过a标签来下载 ,{type: 'application/vnd.ms-excel'}
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      // 此处的download是a标签的内容，固定写法，不是后台api接口
      a.setAttribute('download', decodeURIComponent(filename.split('filename=')[1]));
      document.body.appendChild(a);
      // 点击下载
      a.click();
      // 下载完成移除元素
      document.body.removeChild(a);
      // 释放掉blob对象
      window.URL.revokeObjectURL(url);
      calback(response.data);
    })
    .catch((err) => {
      console.log(err);
      //Message.error('服务异常，请稍后再试!')
    });
}

/* 文件下载 */
export function downloadPostFile(url: string, params = {}, calback: any) {
  const formData = new FormData();
  for (const key in params) {
    // @ts-ignore
    formData.append(key, params[key]);
  }
  axios({
    method: 'post',
    url: url,
    data: formData,
    responseType: 'blob'
  })
    .then((response) => {
      const type = response.data.type;
      if (type == 'application/json') {
        // Message.error('文件不存在');
        return;
      }
      // 进行文件下载
      const filename = response.headers['content-disposition'];
      if (filename == null || filename == '' || filename == undefined) {
        // Message.error('下载失败');
        return;
      }
      const data = response.data;
      if (!data) {
        return;
      }
      // 构造a标签 通过a标签来下载 ,{type: 'application/vnd.ms-excel'}
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      // 此处的download是a标签的内容，固定写法，不是后台api接口
      a.setAttribute('download', decodeURIComponent(filename.split('filename=')[1]));
      document.body.appendChild(a);
      // 点击下载
      a.click();
      // 下载完成移除元素
      document.body.removeChild(a);
      // 释放掉blob对象
      window.URL.revokeObjectURL(url);
      calback(response.data);
    })
    .catch((err) => {
      console.log(err);
      //Message.error('服务异常，请稍后再试!')
    });
}
